<?php
//设置页面编码为 utf-8
header('Content-type: text/html; charset=utf-8');

//获取协议
$pro = explode("/",$_SERVER["SERVER_PROTOCOL"]);
$pro = strtolower($pro[0].'://'.$_SERVER["SERVER_NAME"]);

define('MYURL', $pro);

/**
* 递归创建目录函数
* @param $path 路径，比如 "aa/bb/cc/dd/ee"
* @param $mode 权限值，php中要用0开头，比如0777,0755
*/

function mkdirs($path,$mode)
{
   if (!file_exists($path))
   {
       mkdirs(dirname($path), $mode);
       mkdir($path, $mode);
   }
}

class gethtml{
    public $myurl;
    public $htmlpath;
    public $urlarr;
    
    public function __construct($myurl,$htmlpath) {
        $this->urlarr = array();
        $this->myurl = $myurl;
        $this->htmlpath = $htmlpath;
        
        if(!file_exists($this->htmlpath)){
            mkdir($this->htmlpath,0770);
            chmod($this->htmlpath, 0770);
        }

        $str = file_get_contents($this->myurl);
        file_put_contents($this->htmlpath.'/index.html', $str);
    }
    
    //递归创建不存在的目录
    public function mkdirs($path,$mode){
       if (!file_exists($path))
       {
           $this->mkdirs(dirname($path), $mode);
           mkdir($path, $mode);
       }
    }
    
    //用正则表达式匹配html代码的链接
    public function gethtml($url){
        $str = file_get_contents($url);
        preg_match_all('/href=\"(\/.*.html)\"/', $str, $matches);
        return $matches;
    }
    
    //递归所有链接
    public function checkhref($url){
        if (!in_array($url, $this->urlarr)) {
            echo $url."<br />";
            $this->urlarr[] = $url;
            $data = $this->gethtml($url);
            foreach ($data[1] as $value) {
                $path = dirname($value);
                $this->mkdirs($this->htmlpath.$path,0770);
                chmod($this->htmlpath.$path,0770);
                $code = file_get_contents(MYURL.$value);
                file_put_contents($this->htmlpath.$value, $code);
                $this->checkhref(MYURL.$value);
            }
        }
        
    }
    
}

$gethtml = new gethtml(MYURL,"/var/www/myweb/html");
$gethtml->checkhref($gethtml->myurl);

?>
